package com.xkh.common.service.impl;

import com.xkh.common.common.constant.ConstRedis;
import com.xkh.common.model.dto.NearbyPositionDTO;
import com.xkh.common.model.dto.PositionDTO;
import com.xkh.common.model.vo.UserPositionVO;
import com.xkh.common.service.INearbyService;
import com.xkh.common.util.RedisUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.geo.GeoResult;
import org.springframework.data.geo.GeoResults;
import org.springframework.data.geo.Point;
import org.springframework.data.redis.connection.RedisGeoCommands;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class NearbyServiceImpl implements INearbyService {

    @Autowired
    private RedisUtils redisUtils;

    @Override
    public boolean updatePosition(PositionDTO positionDTO) {
        //用户数据存入到redis中  一般在登录的时候存入
        redisUtils.putHash(ConstRedis.USER_INFO, positionDTO.getUserId(), positionDTO);
        //新增位置数据
        return redisUtils.putGeo(positionDTO);
    }

    @Override
    public List<Point> getPosition(Long userId) {
        return redisUtils.getGeo(userId);
    }

    @Override
    public List<UserPositionVO> getNearbyPosition(NearbyPositionDTO nearbyPositionDTO) {
        List<UserPositionVO> userPositionVOS = new ArrayList<>();
        //3.过滤掉超过距离的数据
        GeoResults<RedisGeoCommands.GeoLocation<Object>> results = redisUtils.getGeoCircle(nearbyPositionDTO);
        //2.收集信息，存入list
        List<GeoResult<RedisGeoCommands.GeoLocation<Object>>> content = results.getContent();
        content.forEach(a -> {
            if(redisUtils.hashKey(ConstRedis.USER_INFO, a.getContent().getName())){
                PositionDTO positionDTO = (PositionDTO) redisUtils.getHash(ConstRedis.USER_INFO, a.getContent().getName());
                if(nearbyPositionDTO.getSex().equals(0) || positionDTO.getSex().equals(nearbyPositionDTO.getSex())){
                    userPositionVOS.add(
                            new UserPositionVO((Long) a.getContent().getName(),
                                    a.getDistance().getValue()));
                }
            }
        });
        return userPositionVOS;

    }

}
